package cn.edu.glut.user.controller;


import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Preconditions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sargeraswang.util.ExcelUtil.ExcelLogs;

import cn.edu.glut.dto.Response;
import cn.edu.glut.dto.StudentInputDTO;
import cn.edu.glut.entity.Major;
import cn.edu.glut.entity.Student;
import cn.edu.glut.user.service.MajorService;
import cn.edu.glut.user.service.StudentService;
import cn.edu.glut.utils.ExcelUtils;
import cn.edu.glut.vo.StudentExcelVo;
import cn.edu.glut.vo.StudentToAdminVO;
import lombok.Cleanup;

/**
 * 
 * @author Caizhfy
 * @email caizhfy@163.com
 * @createTime 2017年12月9日
 * @description 学生操作
 *
 */
@RestController
@RequestMapping("/stu")
public class StudentController {
	@Autowired
	private StudentService studentService;
	@Autowired
	private MajorService majorService;
	
	final Logger logger = LoggerFactory.getLogger(StudentController.class);
	
	//新增
	@RequestMapping("/new")
	public Response save(@Valid StudentInputDTO studentInputDTO){
		return Response.success(studentService.save(studentInputDTO.convertToEntity()));
	}
	
	//上传Excel形式批量增加
	@RequestMapping("/new/upload")
	public Response save(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty())
			return Response.success("文件不能为空");
		if (!ExcelUtils.isExcelFile(file.getOriginalFilename())) {
			return Response.success("请上传正确的Excel文件");
		}
		try {
			ExcelLogs logs = new ExcelLogs();
			Collection<Student> studentList = ExcelUtils.<StudentExcelVo, Student>importExcel(StudentExcelVo.class, Student.class,
					file.getInputStream(), null, 0, logs, getMajorMap());
			if(null!=studentList && studentList.size()!=0)
				studentService.save(studentList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Response.success();
	}
	
	/**
	 * 
	 * @param isSelect	是否选题
	 * @param majorId	根据专业
	 * @param isSelectSuccess 是否选题成功
	 */
	//导出Excel文件
	@RequestMapping("/export")
	public Response export(Boolean isSelect, String majorId, Boolean isSelectSuccess, HttpServletResponse response) throws Exception{
		List<StudentToAdminVO> voList = studentService.list(null, majorId, isSelect, isSelectSuccess).getContent();
		if(voList==null || voList.size()==0)
			return Response.success("目前还没有数据");
		String fileName = getFileName(isSelect, majorId);
		response.setHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("utf-8"),"iso-8859-1"));//解决乱码
		response.setContentType("application/octet-stream;charset=UTF-8");
		
		@Cleanup OutputStream out = response.getOutputStream();
		ExcelUtils.<StudentToAdminVO>exportExcel(StudentToAdminVO.getExcelCellKey(), voList, out);
		return Response.success();
	}
	
	/**
	 * 
	 * @param pageable.page		第几页(默认0)
	 * @param pageable.size		一页的记录数（默认10条每页）
	 * @param isSelect			该学生是否已经选题（非必须）
	 * @param majorId			该学生所属专业（非必须）
	 * @param isSelectSuccess 是否选题成功
	 * @return
	 */
	//@PageableDefault(value = 10, sort = { "id" }, direction = Sort.Direction.DESC)参数代表默认每页十条，根据id逆序排序
	@RequestMapping("/list")
	public Response list(@PageableDefault Pageable pageable, Boolean isSelect, Boolean isSelectSuccess, String majorId){
		return Response.success(studentService.list(pageable, majorId, isSelect, isSelectSuccess));
	}
	
	//查询选择某题目的学生，附带专业等信息（未确选的）
	@RequestMapping("/sub/list/{subjectId}")
	public Response list(@PathVariable String subjectId){
		return Response.success(studentService.listBySubjectId(subjectId));
	}
	
	//根据学号查询，显示给admin
	@RequestMapping("/get/um/{username}")
	public Response getStudentToAdminVOByUsername(@PathVariable String username){
		return Response.success(studentService.findStudentToAdminVOByUsername(username));
	}
	
	@RequestMapping("/update")
	public Response update(@Valid StudentInputDTO studentInputDTO){
		Preconditions.checkNotNull(studentInputDTO.getId(), "id不能为空");
		return Response.success(studentService.update(studentInputDTO.convertToEntity()));
	}
	
	@RequestMapping("/get/{id}")
	public Response get(@PathVariable String id){
		return Response.success(studentService.findById(id));
	}
	
	@RequestMapping("/del/{id}")
	public Response remove(@PathVariable String id){
		studentService.delete(id);
		return Response.success();
	}
	
	//批量删除全部
	@RequestMapping("/dels")
	public Response remove(){
		studentService.deleteAll();
		return Response.success();
	}
	
	
	//map返回键值对：	
	//				专业名称：专业id号码
	private Map<String, String> getMajorMap(){
		Map<String, String> majorMap = null;
		List<Major> majorList = majorService.findAll();
		if(null!=majorList && majorList.size()!=0)
			majorMap = new HashMap<String, String>();
		if(null != majorMap)
		for(Major m : majorList){
			if(!StringUtils.isEmpty(m.getId()) && !StringUtils.isEmpty(m.getName())){
				majorMap.put(m.getName(), m.getId());
			}
		}
		return majorMap;
	}
	
	private String getFileName(Boolean isSelect, String majorId) {
		StringBuffer filename = new StringBuffer("");
		if(majorId!=null){
			Major m = majorService.findById(majorId);
			if(m!=null){
				filename.append(m.getName());
				filename.append("专业");
			}
		}
		if(isSelect!=null)
			if(isSelect)
				filename.append("已选题");
			else
				filename.append("未选题");
		filename.append("学生信息总览");
		filename.append(".xls");
		return filename.toString();
	}
}
